"use strict";
import {
  BrowserWindow,
  Menu,
  app,
  ipcMain,
  screen,
  dialog
} from "electron";
import menuconfig from "./config/menu";
import { winURL } from "./config/StaticPath";
import md5 from "js-md5";
import { IsUseSysTitle } from "./config/const";
import setIpc from "./services/ipcMain";
const request = require("axios");

const path = require("path");
const packageJson = require("../../package.json");
let systemTransfer = {}; //中转数据
let showUpdate;
let updateFrom = {};
let userLogin = false;

request.interceptors.request.use(config => {
  config.headers["Authorization"] = "Basic c2FiZXI6c2FiZXJfc2VjcmV0";
  return config;
})

let newHttp = "http://192.168.4.182:8311/api/"; //公司内网     
let numberLength = 5//本地开发
// let newHttp = "http://172.99.3.165:10100/";//医院内网

request
  .get(`${newHttp}clientVersionUpdates/getLatestVersion`)
  .then((res) => {
    if (res.data.code == 200) {
      updateFrom = res.data.data;
      // console.log(updateFrom, "-----3333");
      if (updateFrom.versionCode > packageJson.version.replaceAll(".", "")) {
        showUpdate = true;
        // console.log(updateFrom, "-----3333");
        // 需要更新跳转到更新页面 并传值
        systemTransfer = {
          error: false,
          show: true,
          closeOpens: true,
          ...updateFrom,
        };
      } else {
        showUpdate = false;
        systemTransfer = {
          error: false,
          show: true,
          closeOpens: false,
          ...updateFrom,
        };
      }
    } else {
      systemTransfer = {
        error: true,
      };
    }
  })
  .catch((err) => {
    systemTransfer = {
      error: true,
    };
  });
var mainWindow; //默认窗口
var levitatedWindow; //悬浮窗
let notification; //更新窗口
let smallClose = false; //关闭小窗口

setIpc.Mainfunc(IsUseSysTitle);

ipcMain.on("getAppName", (e, arg) => {
  createMainWindow();
  levitatedWindow.hide();
  levitatedWindow.close();
});

app.on("ready", () => {
  // let passWord
  // let userName
  let newArrlogin = process.argv.slice(-2)
  let newObjt = {}
  newObjt = {
    userName: newArrlogin[0],
    passWord: newArrlogin[1]
  }
  console.log(process.argv.length, process.argv.slice(-2), newObjt, "用命令cmd启动，然后登录")


  setTimeout(() => {
    if (showUpdate) {
      createWindow();
    } else {
      if (process.argv.length == numberLength) {
        newObjt = {
          ...newObjt,
          newPassWord: md5(newObjt.passWord)
        }
        request
          .post(
            `${newHttp}blade-auth/oauth/token?tenantId=000000&username=${newObjt.userName}&password=${newObjt.newPassWord}&grant_type=password&scope=all&type=account`
          )
          .then((res) => {
            if (res.data.error_code) {
              showAlert(res.data.error_description + '请重新执行命令')
            } else {
              systemTransfer = {
                ...systemTransfer,
                newRes: res.data
              }
              createMainWindow();
            }
          });
      } else {
        createMainWindow();
      }
    }
  }, 2000);
});
// 当另一个实例请求启动应用程序时触发
app.on("second-instance", (event, commandLine, workingDirectory) => {
  ipcMain.send("active", "看看有没效果"); //渲染进程中调用
});

// 主页面
function createMainWindow() {
  menuconfig.push({
    label: "开发者设置",
    submenu: [
      {
        label: "切换到开发者模式",
        accelerator: "CmdOrCtrl+I",
        role: "toggledevtools",
      },
    ],
  });
  // 默认窗口
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    frame: false, //要创建无边框窗口
    resizable: false, //禁止窗口大小缩放
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      contextIsolation: false,
      enableRemoteModule: true,
      // devTools: false,
      webSecurity: false,
      webviewTag: true, // 启用 <webview> tag 标签
    },
  });

  mainWindow.webContents.openDevTools();
  mainWindow.webContents.on("did-finish-load", (event, arg) => {
    mainWindow.webContents.send("setNewData", systemTransfer);
    mainWindow.on("resize", () => {
      mainWindow.webContents.send("windowSize", mainWindow.getBounds());
    });
  });

  const menu = Menu.buildFromTemplate(menuconfig);
  Menu.setApplicationMenu(menu);
  mainWindow.loadURL(winURL);
}

function levitated() {
  // 悬浮窗
  levitatedWindow = new BrowserWindow({
    backgroundColor: '#ffffff', //#80FFFFFF
    width: 100,
    height: 100,
    type: "toolbar", //创建的窗口类型为工具栏窗口
    frame: false, //要创建无边框窗口
    resizable: false, //禁止窗口大小缩放
    transparent: true, //设置透明
    alwaysOnTop: true, //窗口是否总是显示在其他窗口之前
    webPreferences: {
      // sandbox: false, //开启沙箱模式
      webSecurity: false,
      nodeIntegration: true, //添加语句
      contextIsolation: false, //添加语句
    },
  });

  levitatedWindow.webContents.on("did-finish-load", () => {
    levitatedWindow.webContents.send("setNewData", {
      show: false,
      closeOpens: false,
      ...updateFrom,
    });
  });
  levitatedWindow.loadURL(winURL);



  const { left, top } = {
    left: screen.getPrimaryDisplay().workAreaSize.width - 160,
    top: screen.getPrimaryDisplay().workAreaSize.height - 100,
  };
  levitatedWindow.setPosition(left, top); //设置悬浮球位置
}
// 更新页面
function createWindow() {
  notification = new BrowserWindow({
    width: 600,
    height: 400,
    resizable: false, //禁止窗口大小缩放
    frame: false, //要创建无边框窗口
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      contextIsolation: false,
      webviewTag: true, // 启用 <webview> tag 标签
    },
  });
  notification.webContents.on("did-finish-load", () => {
    notification.webContents.send("setNewData", systemTransfer);
    notification.webContents.send("setNewupData", updateFrom);
  });

  // notification.webContents.openDevTools();
  notification.loadURL(winURL);
}

ipcMain.on("notification-message", (event, arg) => {
  if (!arg.closeOpen) {
    notification.hide();
    createMainWindow();
    notification.destroy();
  }
});

// 登录传送过来的信息
ipcMain.on("userLogin-message", (event, arg) => {
  userLogin = true;
});

ipcMain.on("renewal", (e, arg) => {
  if (!arg.isUpdate) {
    createMainWindow();
    notification = null;
    notification.close();
  }
});

ipcMain.on("close-win", (e, arg) => {
  if (arg.closeSmall) {
    mainWindow.hide();
    mainWindow.close();
    levitated();
    return;
  }
  if (arg.closeUpdate) {
    notification.hide();
    setTimeout(() => {
      notification.close();
    }, 10000);
    return;
  }
});

app.on("window-all-closed", (e, arg) => {
  if (!smallClose) app.quit();
});

function showAlert(message) {
  dialog.showMessageBox({
    type: 'error',
    title: 'VTE',
    message: message,
    buttons: ['确定']
  }).then(response => {
    console.log('提示框已关闭');
    app.quit();
  });
}

